﻿using ICSharpCode.SharpZipLib.Zip;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace jvm.classpath
{
    class JarEntry : Entry
    {
        ZipFile jarFile;
        Dictionary<string, ZipEntry> entries = new Dictionary<string, ZipEntry>();

        public JarEntry(string path) : base(path)
        {
            if (!File.Exists(path))
            {
                Console.WriteLine("Cannot find {0} in the environment!", path);
                Environment.Exit(0);
            }

            jarFile = new ZipFile(path);

            ZipInputStream zipIn = new ZipInputStream(File.OpenRead(path));
            ZipEntry theEntry;
            while ((theEntry = zipIn.GetNextEntry()) != null)
            {
                string name = theEntry.Name;
                name = name.Replace('\\', '.');
                name = name.Replace('/', '.');
                entries[name] = theEntry;
            }
        }

        public override Tuple<bool, byte[], Entry> ReadClass(string classname)
        {
            classname = classname.Replace('\\', '.');
            classname = classname.Replace('/', '.');
            if (entries.ContainsKey(classname))
            {
                ZipEntry entry = entries[classname];
                byte[] bytes = new byte[entry.Size];
                jarFile.GetInputStream(entry).Read(bytes, 0, bytes.Length);
                return new Tuple<bool, byte[], Entry>(true, bytes, this);
            }
            return new Tuple<bool, byte[], Entry>(false, null, this);
        }
    }
}
